/*
 * Copyright 2002-2006 the original author or authors. Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language governing permissions and limitations under the
 * License.
 */
package pikes.samples.countries.ui.peak;

import java.util.Collection;
import java.util.Map;

import org.springframework.samples.countries.web.bom.History;
import org.springframework.web.servlet.support.RequestContext;

import pikes.ecma.ExpressionStatement;
import pikes.ecma.FunctionCall;
import pikes.ecma.MemberPropertyAccess;
import pikes.ecma.SourceElement;
import pikes.peak.Composite;
import pikes.peak.Label;
import pikes.peak.LabelStyle;
import pikes.peak.RequestProperty;
import pikes.peak.Paragraph;
import pikes.peak.TextGroupStyle;

public class ErrorPage extends BehaviourPage {

	private History history = new History();

	@Override
	protected void translate(Collection<DynamicSourceElements> declaredCode) {
		DynamicSourceElements dynamincSourceElements = new DynamicSourceElements();

		DynamicFunctionDeclaration dynamicFunction = new DynamicFunctionDeclaration("back");
		FunctionCall call = new FunctionCall(new MemberPropertyAccess("history", "go"), "-1");
		dynamicFunction.addCode(call);

		dynamincSourceElements.addSourceElement(dynamicFunction);
		declaredCode.add(dynamincSourceElements);
	}

	@org.springframework.samples.countries.web.translate.ClientSide
	protected void back() {
		history.go(-1);
	}

	@Override
	protected String getTitle() {
		return "error.http404.htitle";
	}

	@Override
	protected void buildContent(Composite content) {
		content.add(new Paragraph("error.http404.title", TextGroupStyle.LEVEL_2));

		content.add(Label.LINE_BREAK);
		content.add(Label.LINE_BREAK);

		content.add(new Paragraph("error.http404.txt"));

		content.add(Label.LINE_BREAK);

		Composite backDiv = new Composite();
		Label label = new Label("gen.back", LabelStyle.STRONG);

		/*
		 * label.setURI(new EventHandlerURI(new EventHandler() { @Override protected void onEvent() { back(); } }));
		 */
		label.setURI(new EventHandlerURI(new RequestProperty<SourceElement>() {

			public SourceElement getValue(Map model, RequestContext requestContext) throws Exception {
				return new ExpressionStatement(new FunctionCall("back"));
			}

		}));

		backDiv.add(label);
		content.add(backDiv);
	}

}
